package com.tongcao.cn.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

/**
 * @Author:tongcao
 * @Date:2018/8/23 19:43
 * Description:
 */
public class URLEncoderUtil {
    /**
     * encode msg,页面上显示使用
     *
     * @param message
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String urlEncoder(String message) throws UnsupportedEncodingException {
        message = message.replaceAll("%", "%25");
        message = message.replaceAll(" ", "%20");
        message = message.replaceAll("\\+", "%2B");
        message = message.replaceAll("/", "%2F");
        message = message.replaceAll("\\?", "%3F");
        message = message.replaceAll("#", "%23");
        message = message.replaceAll("&", "%26");
        message = message.replaceAll("=", "%3D");
        return URLEncoder.encode(message, "UTF-8");
    }

    public static String urlEncode(String s, String charset) {
        try {
            return URLEncoder.encode(s, charset);
        } catch (UnsupportedEncodingException e) {
            throw new UnsupportedOperationException(e);
        }
    }

    /**
     * 生成URL使用的查询参数,不encode
     *
     * @param params
     * @return
     */
    public static String getQueryParams(Map<?, ?> params) {
        return urlEncode(params, null);
    }

    /**
     * @param params
     * @return
     */
    public static String urlEncode(Map<?, ?> params, String charset) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<?, ?> entry : params.entrySet()) {
            if (null != entry.getValue()) {
                if (sb.length() > 0) {
                    sb.append("&");
                }
                String _k = entry.getKey().toString();
                String _v = entry.getValue().toString();
                sb.append(String.format("%s=%s",
                        (null == charset) ? _k : urlEncode(_k, charset),
                        (null == charset) ? _v : urlEncode(_v, charset)));
            }
        }
        return sb.toString();
    }

    public static String urlEncodeUTF8(Map<?, ?> map) {
        return urlEncode(map, "UTF-8");
    }

    public static void main(String[] args) throws UnsupportedEncodingException {
        String encoderMessage = urlEncoder("sutiao 112");
        System.out.println(URLEncoder.encode("sutiao 112", "UTF-8"));
        System.out.println("encoderMessage:" + encoderMessage);
        String decodeMessage = URLDecoder.decode(encoderMessage, "UTF-8");
        System.out.println("decodeMessage:" + decodeMessage);
    }


}
